package com.cn.redisDemo; /**
 * @author: yihanyuan
 * @Description：
 * @Date: 2018/12/4 10:45
 */


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @program: demo
 * @description:
 * @author: yihanyuan
 * @create: 2018-12-04 10:45
 **/
public class RedisClient {
    private OutputStream outputStream;
    private InputStream inputStream;

    public RedisClient(String host, int port) throws IOException {
        Socket socket = new Socket(host, port);
        outputStream = socket.getOutputStream();
        inputStream = socket.getInputStream();
    }

    public void set(String key, String value) throws IOException {
        StringBuffer sb = new StringBuffer();
        //第三个参数
//        sb.append("*3").append("\r\n");
//        sb.append("$3").append("\r\n");
//        sb.append("SET").append("\r\n");
//        sb.append("$").append(key.getBytes().length).append("\r\n");
        sb.append(key).append("\r\n");
//        sb.append("$").append(value.getBytes().length).append("\r\n");
        sb.append(value).append("\r\n");
        outputStream.write(sb.toString().getBytes());
        System.out.println("发送到客户端：" + sb);
        byte[] response = new byte[1024];
        inputStream.read(response);
        System.out.println("接收响应：" + new String(response));
    }

    public void get(String key) throws IOException {
        StringBuffer sb = new StringBuffer();
//        sb.append("*2").append("\r\n");
//        sb.append("$3").append("\r\n");
//        sb.append("GET").append("\r\n");
//        sb.append("$").append(key.getBytes().length).append("\r\n");
        sb.append(key).append("\r\n");
        outputStream.write(sb.toString().getBytes());
        byte[] bytes = new byte[1024];
        inputStream.read(bytes);
        System.out.println(new String(bytes));
    }

    public static void main(String[] args) throws IOException {
        RedisClient redisClient = new RedisClient("127.0.0.1", 6379);
        redisClient.set("name", "易汉渊");
        redisClient.set("name1", "易汉渊1");
        redisClient.get("name");
        redisClient.get("name1");
    }
}
